package com.world.cat.service.sys;

import com.world.cat.dao.sys.RoleResourceDao;
import com.world.cat.dao.sys.UserRoleDao;
import com.world.cat.model.sys.RoleResource;
import com.world.cat.model.sys.UserRole;
import com.world.cat.task.TaskWorker;
import com.world.common.util.CollectionUtil;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by gang on 2017/11/28.
 */
@Service
@Transactional
public class ApiVerifyService {
    private static final Logger logger = Logger.getLogger(ApiVerifyService.class);

    @Resource
    private UserRoleDao userRoleDao;
    @Resource
    private RoleResourceDao roleResourceDao;

    public boolean verifyApiUrl(String userId, String url) {
        List<RoleResource> roleResources = roleResourceDao.findByUrl(url);
        //并没有角色控制该url，则默认该url是开放访问的
        if (CollectionUtil.isEmpty(roleResources)) {
            logger.warn("url:" + url + "未设置权限");
            return true;
        }
        Set<String> roleIds = new HashSet<>();
        for (RoleResource roleResource : roleResources) {
            roleIds.add(roleResource.getRoleId());
        }
        List<UserRole> userRoles = userRoleDao.findByUserId(userId);
        if (CollectionUtil.isNotEmpty(userRoles)) {
            for (UserRole userRole : userRoles) {
                if (roleIds.contains(userRole.getRoleId())) {
                    return true;
                }
            }
        }
        return false;
    }
}
